// package: rewords-server-2024
// filename: mgx
// author: diogoxiang@gmail.com
// time: 2024/7/31 下午3:46

package mgx

import (
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"rewords-server-2024/internal/library/cfg"
	"rewords-server-2024/internal/library/xpool"
	"time"
)

const (
	// CounterCollection 自增 collection
	CounterCollection = "counters"
)

// CheckUpdateContent 执行更新操作之前先判断有没有$操作符
func CheckUpdateContent(update bson.M) error {
	for k := range update {
		if k[0] != '$' {
			return errors.New("update content must start with '$'")
		}
	}
	return nil
}

// ExcludeDeleted 不包含已删除的
func ExcludeDeleted(selector bson.M) bson.M {
	selector["deleted_at"] = bson.M{"$exists": false}
	return selector
}

// UpdatedTime UpdatedAt
func UpdatedTime(update bson.M) bson.M {
	if v, ok := update["$set"]; ok {
		v.(bson.M)["updated_at"] = time.Now()
	} else {
		update["$set"] = bson.M{"updated_at": time.Now()}
	}
	return update
}

// DeletedTime 更新deletedAt时间
func DeletedTime(update bson.M) bson.M {
	if v, ok := update["$set"]; ok {
		v.(bson.M)["deleted_at"] = time.Now()
	} else {
		update["$set"] = bson.M{"deleted_at": time.Now()}
	}
	return update
}

// GetAutoInc  获取自增参数
func GetAutoInc(name string) (id int, err error) {
	var (
		client *mongo.Client
		p      interface{}
	)
	p, err = xpool.GMongoPool.Get()
	defer xpool.GMongoPool.Put(p)
	client = p.(*mongo.Client)
	collection := client.Database(cfg.GConfig.Mongo.DbName).Collection(CounterCollection)

	id, err = AutoInc(collection, name)
	if err != nil {
		return 0, err
	}
	return id, nil
}
